// pages/capsule/edit.js
const Toast = require('@vant/weapp/toast/toast')
const Dialog = require('@vant/weapp/dialog/dialog')

/**
 * 编辑页面数据接口
 * @typedef {Object} IEditData
 * @property {string} capsuleId
 * @property {any} originalData
 * @property {string} title
 * @property {string} description
 * @property {string} coverImage
 * @property {string} selectedTemplate
 * @property {boolean} isPrivate
 * @property {boolean} allowShare
 * @property {any} capsuleStats
 * @property {boolean} isLoading
 * @property {boolean} isSaving
 * @property {boolean} isDeleting
 * @property {boolean} showCoverModal
 * @property {boolean} showDeleteModal
 * @property {string} deleteConfirmText
 * @property {boolean} canSave
 * @property {boolean} canDelete
 * @property {string} titleError
 * @property {Array<{name: string, text: string}>} coverActions
 */

Page({
  data: {
    // 胶囊ID
    capsuleId: '',
    
    // 原始数据
    originalData: {},
    
    // 表单数据
    title: '',
    description: '',
    coverImage: '',
    selectedTemplate: '',
    isPrivate: true,
    allowShare: false,
    
    // 统计数据
    capsuleStats: null,
    
    // 状态
    isLoading: true,
    isSaving: false,
    isDeleting: false,
    showCoverModal: false,
    showDeleteModal: false,
    
    // 删除确认
    deleteConfirmText: '',
    
    // 计算属性
    canSave: false,
    canDelete: false,
    
    // 错误信息
    titleError: '',
    
    // 封面选择操作
    coverActions: [
      { name: 'album', text: '从相册选择' },
      { name: 'camera', text: '拍照' }
    ]
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ capsuleId: options.id })
      this.checkLoginStatus()
      this.loadCapsuleData()
    } else {
      Toast.fail('参数错误')
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token')
    if (!token) {
      Dialog.alert({
        title: '提示',
        message: '请先登录'
      }).then(() => {
        wx.redirectTo({
          url: '/pages/login/login'
        })
      })
      return
    }
  },

  // 加载胶囊数据
  async loadCapsuleData() {
    try {
      this.setData({ isLoading: true })
      const token = wx.getStorageSync('token')
      
      const [capsuleResult, statsResult] = await Promise.all([
        new Promise((resolve, reject) => {
          wx.request({
            url: `https://api.example.com/api/memory-capsules/${this.data.capsuleId}`,
            method: 'GET',
            header: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
            success: resolve,
            fail: reject
          })
        }),
        new Promise((resolve, reject) => {
          wx.request({
            url: `https://api.example.com/api/memory-capsules/${this.data.capsuleId}/stats`,
            method: 'GET',
            header: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
            success: resolve,
            fail: reject
          })
        })
      ])

      if (capsuleResult.statusCode === 200) {
        const capsule = capsuleResult.data
        this.setData({
          originalData: capsule,
          title: capsule.title || '',
          description: capsule.description || '',
          coverImage: capsule.coverImage || '',
          selectedTemplate: capsule.template || '',
          isPrivate: capsule.isPrivate !== false,
          allowShare: capsule.allowShare === true
        })
        
        // 初始验证
        this.validateForm()
      } else {
        throw new Error('加载失败')
      }
      
      if (statsResult.statusCode === 200) {
        this.setData({
          capsuleStats: statsResult.data
        })
      }
    } catch (error) {
      console.error('加载胶囊数据失败:', error)
      Toast.fail(error.message || '加载失败')
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } finally {
      this.setData({ isLoading: false })
    }
  },

  // 标题输入
  onTitleInput(e) {
    const title = e.detail.value
    this.setData({ title })
    this.validateForm()
  },

  // 描述输入
  onDescriptionInput(e) {
    const description = e.detail.value
    this.setData({ description })
    this.validateForm()
  },

  // 表单验证
  validateForm() {
    const { title, description, coverImage, selectedTemplate, isPrivate, allowShare, originalData } = this.data
    
    // 检查是否有修改
    const hasChanges = (
      title !== (originalData.title || '') ||
      description !== (originalData.description || '') ||
      coverImage !== (originalData.coverImage || '') ||
      selectedTemplate !== (originalData.template || '') ||
      isPrivate !== (originalData.isPrivate !== false) ||
      allowShare !== (originalData.allowShare === true)
    )
    
    // 检查必填项
    const isValid = title.trim().length > 0
    const titleError = title.trim().length === 0 ? '请输入胶囊标题' : ''
    
    this.setData({
      canSave: hasChanges && isValid,
      titleError
    })
  },

  // 选择封面
  onSelectCover() {
    this.setData({
      showCoverModal: true
    })
  },

  // 更换封面
  onChangeCover() {
    this.setData({
      showCoverModal: true
    })
  },

  // 移除封面
  onRemoveCover() {
    this.setData({
      coverImage: ''
    })
    this.validateForm()
  },

  // 隐藏封面选择弹窗
  hideCoverModal() {
    this.setData({
      showCoverModal: false
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 封面操作选择
  onCoverActionSelect(e) {
    const { name } = e.detail
    this.hideCoverModal()
    
    if (name === 'album') {
      this.onSelectFromAlbum()
    } else if (name === 'camera') {
      this.onTakePhoto()
    }
  },

  // 从相册选择
  onSelectFromAlbum() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        if (res.tempFiles && res.tempFiles.length > 0) {
          this.uploadCoverImage(res.tempFiles[0].tempFilePath)
        }
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        Toast.fail('选择图片失败')
      }
    })
  },

  // 拍照
  onTakePhoto() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      success: (res) => {
        if (res.tempFiles && res.tempFiles.length > 0) {
          this.uploadCoverImage(res.tempFiles[0].tempFilePath)
        }
      },
      fail: (err) => {
        console.error('拍照失败:', err)
        Toast.fail('拍照失败')
      }
    })
  },

  // 上传封面图片
  async uploadCoverImage(filePath) {
    try {
      wx.showLoading({ title: '上传中...' })
      const token = wx.getStorageSync('token')
      
      const uploadResult = await new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://api.example.com/api/upload/image',
          filePath,
          name: 'file',
          header: {
            'Authorization': `Bearer ${token}`
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (res.statusCode === 200 && data.url) {
                resolve(data)
              } else {
                reject(new Error(data.message || '上传失败'))
              }
            } catch (e) {
              reject(new Error('解析响应失败'))
            }
          },
          fail: reject
        })
      })
      
      this.setData({
        coverImage: uploadResult.url
      })
      
      this.validateForm()
      wx.hideLoading()
      Toast.success('上传成功')
    } catch (error) {
      wx.hideLoading()
      console.error('上传封面失败:', error)
      Toast.fail(error.message || '上传失败')
    }
  },

  // 选择模板
  onSelectTemplate(e) {
    const template = e.currentTarget.dataset.template
    this.setData({
      selectedTemplate: template
    })
    this.validateForm()
  },

  // 隐私设置变化
  onPrivacyChange(e) {
    const isPrivate = e.detail.value
    this.setData({
      isPrivate,
      allowShare: isPrivate ? false : this.data.allowShare
    })
    this.validateForm()
  },

  // 分享设置变化
  onShareChange(e) {
    this.setData({
      allowShare: e.detail.value
    })
    this.validateForm()
  },

  // 删除胶囊
  onDeleteCapsule() {
    this.setData({
      showDeleteModal: true,
      deleteConfirmText: ''
    })
  },

  // 隐藏删除弹窗
  hideDeleteModal() {
    this.setData({
      showDeleteModal: false,
      deleteConfirmText: ''
    })
  },

  // 删除确认输入
  onDeleteConfirmInput(e) {
    const deleteConfirmText = e.detail.value
    this.setData({
      deleteConfirmText,
      canDelete: deleteConfirmText === this.data.title
    })
  },

  // 确认删除
  async confirmDelete() {
    if (!this.data.canDelete || this.data.isDeleting) {
      return
    }

    try {
      this.setData({ isDeleting: true })
      const token = wx.getStorageSync('token')
      
      const result = await new Promise((resolve, reject) => {
        wx.request({
          url: `https://api.example.com/api/memory-capsules/${this.data.capsuleId}`,
          method: 'DELETE',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          success: resolve,
          fail: reject
        })
      })

      if (result.statusCode === 200) {
        Toast.success('删除成功')
        
        // 延迟跳转
        setTimeout(() => {
          wx.navigateBack({
            delta: 2 // 返回到首页
          })
        }, 1500)
      } else {
        throw new Error('删除失败')
      }
    } catch (error) {
      console.error('删除胶囊失败:', error)
      Toast.fail(error.message || '删除失败')
    } finally {
      this.setData({ isDeleting: false })
    }
  },

  // 取消编辑
  onCancel() {
    if (this.data.canSave) {
      Dialog.confirm({
        title: '确认取消',
        message: '当前修改将不会保存，确定要取消吗？'
      }).then(() => {
        wx.navigateBack()
      }).catch(() => {
        // 用户取消
      })
    } else {
      wx.navigateBack()
    }
  },

  // 保存修改
  async onSave() {
    if (!this.data.canSave || this.data.isSaving) {
      return
    }

    try {
      this.setData({ isSaving: true })
      const token = wx.getStorageSync('token')
      
      const requestData = {
        title: this.data.title.trim(),
        description: this.data.description.trim(),
        coverImage: this.data.coverImage,
        template: this.data.selectedTemplate,
        isPrivate: this.data.isPrivate,
        allowShare: this.data.allowShare
      }

      const result = await new Promise((resolve, reject) => {
        wx.request({
          url: `https://api.example.com/api/memory-capsules/${this.data.capsuleId}`,
          method: 'PUT',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: requestData,
          success: resolve,
          fail: reject
        })
      })

      if (result.statusCode === 200) {
        Toast.success('保存成功')
        
        // 延迟跳转
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        throw new Error('保存失败')
      }
    } catch (error) {
      console.error('保存胶囊失败:', error)
      Toast.fail(error.message || '保存失败')
    } finally {
      this.setData({ isSaving: false })
    }
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return ''
    
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    
    // 小于1分钟
    if (diff < 60 * 1000) {
      return '刚刚'
    }
    
    // 小于1小时
    if (diff < 60 * 60 * 1000) {
      const minutes = Math.floor(diff / (60 * 1000))
      return `${minutes}分钟前`
    }
    
    // 小于1天
    if (diff < 24 * 60 * 60 * 1000) {
      const hours = Math.floor(diff / (60 * 60 * 1000))
      return `${hours}小时前`
    }
    
    // 小于7天
    if (diff < 7 * 24 * 60 * 60 * 1000) {
      const days = Math.floor(diff / (24 * 60 * 60 * 1000))
      return `${days}天前`
    }
    
    // 格式化为具体日期
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    
    if (year === now.getFullYear()) {
      return `${month}-${day} ${hour}:${minute}`
    } else {
      return `${year}-${month}-${day} ${hour}:${minute}`
    }
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: `${this.data.title} - 永恒之爱`,
      path: `/pages/capsule/detail?id=${this.data.capsuleId}`,
      imageUrl: this.data.coverImage || '/images/share-cover.jpg'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: `${this.data.title} - 永恒之爱`,
      imageUrl: this.data.coverImage || '/images/share-cover.jpg'
    }
  }
})